package com.core.pdf;

import cn.hutool.core.date.DateUtil;
import com.itextpdf.barcodes.Barcode128;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 打印条形码
 */
@Slf4j
public class PdfHelper1 {


    /**
     * 打印
     *
     * @param barCode
     * @return
     */
    public void printPdf(String barCode) throws Exception {
        String tempDir = OpcUaConfig.getInstance().getBarcodeTempDir();
        String printName = OpcUaConfig.getInstance().getPrintName();
        String outFilePath;
        if (tempDir == null || tempDir.trim().length() == 0) {
            outFilePath = "E://mes/server/lock";
        } else {
            outFilePath = tempDir;
        }
        Date now = new Date();
        String date = DateUtil.format(now, "yyyyMMdd");
        Long dateTime = System.currentTimeMillis();
        if (outFilePath.endsWith("/") || outFilePath.endsWith("\\")) {
            outFilePath += date + "/" + barCode + "_" + dateTime + ".pdf";
        } else {
            outFilePath += "/" + date + "/" + barCode + "_" + dateTime + ".pdf";
        }
        File outFile = new File(outFilePath);
        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }
        PdfDocument pdf = null;
        PdfWriter writer = null;
        PDDocument printDocument = null;

        try {
            //生产条码PDF
            writer = new PdfWriter(outFile);
            pdf = new PdfDocument(writer);
            //宽，高
            Document document = new Document(pdf, new PageSize(160F, 42F));
            // 添加条形码
            Barcode128 barcode = new Barcode128(pdf);
            barcode.setCode(barCode);
            //条码报读
            barcode.setBarHeight(40F);
            Image code = new Image(barcode.createFormXObject(ColorConstants.BLACK, ColorConstants.BLACK, pdf));
            code.setWidth(156F);
            code.setFixedPosition(2, 1);
            document.add(code);
            document.close();


            //打印
            printDocument = PDDocument.load(outFile);
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setJobName("P" + barCode);
            job.setPrintService(getPrintService(printName));
            job.setPageable(new PDFPageable(printDocument));

            Paper paper = new Paper();
            int width = 170;
            int height = 45;
            //A6纸宽度297高421
            //A4纸宽度595高842
            // 设置打印纸张大小
            paper.setSize(width, height); // 1/72 inch
            // 设置边距，单位是像素，10mm边距，对应 28px
            int marginLeft = 0;
            int marginRight = 0;
            int marginTop = 0;
            int marginBottom = 0;
            // 设置打印位置 坐标
            paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));


            // custom page format
            PageFormat pageFormat = new PageFormat();

            pageFormat.setPaper(paper);
            // override the page format
            Book book = new Book();
            // append all pages 设置一些属性 是否缩放 打印张数等
            book.append(new PDFPrintable(printDocument, Scaling.ACTUAL_SIZE), pageFormat, 1);
            job.setPageable(book);
            // 开始打印
            job.print();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ex) {
                }
            }
            if (pdf != null) {
                try {
                    pdf.close();
                } catch (Exception ex) {
                }
            }
            if (printDocument != null) {
                try {
                    printDocument.close();
                } catch (Exception ex) {
                }
            }
        }

    }


    //取得打印机
    private static PrintService printService = null;

    /**
     * 取得打印机
     *
     * @return
     */
    private static PrintService getPrintService(String printName) throws Exception {
        if (printService == null) {
            // 查找并设置打印机
            // 获得本台电脑连接的所有打印机
            PrintService[] printServices = PrinterJob.lookupPrintServices();
            if (printServices == null || printServices.length == 0) {
                log.error("打印失败，未找到可用打印机，请检查。");
                throw new Exception("打印失败，未找到可用打印机，请检查。");
            }

            //匹配指定打印机
            for (int i = 0; i < printServices.length; i++) {
                if (printServices[i].getName().equals(printName)) {
                    printService = printServices[i];
                    break;
                }
            }
        }
        return printService;
    }


}
